﻿using MyTodo.Shared.Services;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyTodo.Services;

public class HttpRestClient
{
    protected readonly RestClient _client;
    public HttpRestClient(string apiUrl)
    {
        _client = new RestClient(apiUrl);
    }

    public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest)
    {
        var request = new RestRequest(baseRequest.Route, baseRequest.Method)
            .AddHeader("Content-Type", baseRequest.ContentType);
        if (baseRequest.Parameter != null)
        {
            request.AddJsonBody(JsonConvert.SerializeObject(baseRequest.Parameter));
        }
        RestResponse response = await _client.ExecuteAsync(request);
        if (response == null || string.IsNullOrEmpty(response.Content))
        {
            return new ApiResponse("请求失败！");
        }
        var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(response.Content);
        if (apiResponse == null)
        {
            return new ApiResponse("请求结果异常！");
        }
        return apiResponse;
    }

    public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
    {
        try
        {
            var request = new RestRequest(baseRequest.Route, baseRequest.Method)
                .AddHeader("Content-Type", baseRequest.ContentType);
            if (baseRequest.Parameter != null)
            {
                request.AddJsonBody(JsonConvert.SerializeObject(baseRequest.Parameter));
            }
            RestResponse response = await _client.ExecuteAsync(request);
            if (response == null || string.IsNullOrEmpty(response.Content))
            {
                return new ApiResponse<T>("请求失败！");
            }
            var apiResponse = JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);
            if (apiResponse == null)
            {
                return new ApiResponse<T>("请求结果异常！");
            }
            return apiResponse;
        }
        catch (Exception ex)
        {
            return new ApiResponse<T>($"请求结果异常！{ex.Message}");
        }
    }
}
